package com.bootdo.system.controller;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.bootdo.app.common.utils.PayUtil;
import com.bootdo.app.dto.wx.TemplateMsgRequest;
import com.bootdo.app.service.UserGroupBuyService;
import com.bootdo.app.service.WXService;
import com.bootdo.app.vo.miniprogram.GroupBuyJoinerVo;
import com.bootdo.app.vo.miniprogram.UserGroupBuyVo;
import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.utils.CheckoutUtil;
import com.bootdo.common.utils.DateUtils;
import com.bootdo.common.utils.HttpUtil;
import com.bootdo.common.utils.xstream;
import com.bootdo.common.wx.WeiXinUtil;
import com.bootdo.common.wx.WeixinOauth2Token;
import com.bootdo.system.domain.TbScgl;
import com.bootdo.system.domain.TbWeixinconfig;
import com.bootdo.system.domain.TbWxmenu;
import com.bootdo.system.domain.TbWxmessage;
import com.bootdo.system.domain.TbWxuser;
import com.bootdo.system.service.MsgService;
import com.bootdo.system.service.ScglService;
import com.bootdo.system.service.WxConfigService;
import com.bootdo.system.service.WxMenuService;
import com.bootdo.system.service.WxUserService;

import net.sf.json.JSONObject;

@RestController
@RequestMapping(value = "/wxConfig")
public class WxController {
	
	private static Map<String,String> mediaMap=new HashMap<String,String>();
	
	
	@Autowired
	private WxUserService wxUserService;
	
	@Autowired
	private WxConfigService wxConfigService;
	
	@Autowired
	private UserGroupBuyService userGroupBuyService;
	
	@Autowired
	private WXService wXService;
	@Autowired
	private BootdoConfig bootdoConfig;
	
	@Autowired
	private WxMenuService wxMenuService;
	
	@Autowired
	private ScglService scglService;
	@Autowired
	private MsgService msgService;
	
	//微信获取用户信息
    @RequestMapping("/WeiXinCode2")
    public ModelAndView WeiXinTest2(ModelMap map, Integer userId,HttpServletRequest request, HttpServletResponse response) throws IOException{
    	ModelAndView mav = new ModelAndView();
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String code = request.getParameter("code");
        mav.setViewName("info");
        return mav;
    }
	
		//微信获取用户信息
	    @RequestMapping("/WeiXinCode")
	    public ModelAndView WeiXinTest(ModelMap map, Integer userId,HttpServletRequest request, HttpServletResponse response) throws IOException{
	    	ModelAndView mav = new ModelAndView();
	        request.setCharacterEncoding("utf-8");
	        response.setCharacterEncoding("utf-8");
	        String code = request.getParameter("code");
	        // 通过code获取access_token
	        WeixinOauth2Token oauth2Token =WeiXinUtil.getOauth2AccessToken(WeiXinUtil.appid, WeiXinUtil.appSecret, code);
//	        WeixinOauth2Token oauth2Token =WeiXinUtil.getOauth2AccessToken("wxcb74c2a7fb1fd161","3ba771e951e1e0e917b7dcd777a25e06", code);
	        String openId=oauth2Token.getOpenId();
	        TbWxuser table=new TbWxuser();
	        table.setId(userId);
	        table.setOpenid(openId);
			wxUserService.insert2update(table);
	        mav.setViewName("info");
	        return mav;
	    }
	    
	    /**
		 * @return
		 * @throws Exception
		 * @Description:
		 */
		@RequestMapping("/gzhNotify")
		public void wxNotify(Integer sid,HttpServletRequest request, HttpServletResponse response) throws Exception {
			 boolean isGet = request.getMethod().toLowerCase().equals("get");
		        PrintWriter print;
		        if (isGet) {
		            // 微信加密签名
		            String signature = request.getParameter("signature");
		            // 时间戳
		            String timestamp = request.getParameter("timestamp");
		            // 随机数
		            String nonce = request.getParameter("nonce");
		            // 随机字符串
		            String echostr = request.getParameter("echostr");
		            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		            if (signature != null && CheckoutUtil.checkSignature(signature, timestamp, nonce)) {
		                try {
		                    print = response.getWriter();
		                    print.write(echostr);
		                    print.flush();
		                    //return;
		                } catch (IOException e) {
		                    e.printStackTrace();
		                }
		            }
		        }
			
			BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
			String line = null;
			StringBuilder sb = new StringBuilder();
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			br.close();
			// sb为微信返回的xml
			String notityXml = sb.toString();
			System.out.println("接收到的报文：" + notityXml);
			Map map = PayUtil.doXMLParse(notityXml);
			String FromUserName =(String) map.get("FromUserName");
			
			
			
			String EventKey =(String) map.get("EventKey");
			String Event =(String) map.get("Event");
			
			String MsgType =(String) map.get("MsgType");
			if("text".equals(MsgType)) {
				String Content =(String) map.get("Content");
				TbWxmessage table=new TbWxmessage();
				table.setAdminId(sid);
				table.setTitle(FromUserName);
				table.setCategory(2);
				table.setMessageContent(Content);
				msgService.insert2update(table);
			}
			if("CLICK".equals(Event)) {
				TbWxmenu selectByUserId66 = wxMenuService.selectByUserId(sid);
				String AppId = selectByUserId66.getAppid();
				 String Appsecret = selectByUserId66.getAppsecret();
				 String accessToken= wXService.getAccessToken(AppId, Appsecret);
				if("col_2".equals(EventKey)) {
					if(mediaMap.containsKey(sid+"@"+"col_2")) {
						String mediaId = mediaMap.get(sid+"@"+"col_2");
						sendMsg5(accessToken, FromUserName, mediaId);
					}else {
						String uploadPath = bootdoConfig.getUploadPath()+"1.png";
						JSONObject addMaterialEver = addMaterialEver(uploadPath,"",accessToken);
						 String media_id = (String) addMaterialEver.get("media_id");
						 mediaMap.put(sid+"@"+"col_2", media_id);
						 sendMsg5(accessToken, FromUserName, media_id);
					}
//					sendMsg3(accessToken, FromUserName, "微信缴费使用指南2","",bootdoConfig.getSsl()+"/upLoad/1.png", "");
				}else {
					if(mediaMap.containsKey(sid+"@"+"col_1")) {
						String mediaId = mediaMap.get(sid+"@"+"col_1");
						sendMsg5(accessToken, FromUserName, mediaId);
					}else {
						String uploadPath = bootdoConfig.getUploadPath()+"20170831595cf16beb634972a65adb6b14abca9b.jpg";
						JSONObject addMaterialEver = addMaterialEver(uploadPath,"",accessToken);
						 String media_id = (String) addMaterialEver.get("media_id");
						 mediaMap.put(sid+"@"+"col_1", media_id);
						 sendMsg5(accessToken, FromUserName, media_id);
					}
//					sendMsg3(accessToken, FromUserName, "微信缴费使用指南1", "", bootdoConfig.getSsl()+"/upLoad/20170831595cf16beb634972a65adb6b14abca9b.jpg", "");
				}
			}
			System.out.println(Event);
			boolean falg=false;
			if(EventKey != null) {
				if(EventKey.contains("qrscene_")) {
					falg=true;
					EventKey= EventKey.split("qrscene_")[1];
				}
			}
			if(StringUtils.isNoneBlank(EventKey)) {
				
				TbWxmenu selectByUserId66 = wxMenuService.selectByUserId(sid);
				String AppId = selectByUserId66.getAppid();
				 String Appsecret = selectByUserId66.getAppsecret();
				String[] split = EventKey.split("@");
				String type = split[0];
				if("pt".equals(type)) {
					//走邀请逻辑
					String wxUserId = split[1];
//					String AppId = split[2];
//					String Appsecret = split[3];
					Integer id=null;
				      String accessToken= wXService.getAccessToken(AppId, Appsecret);

//				    String accessToken =WeiXinUtil.getOauth2AccessToken2(AppId, Appsecret);
				    String res = getUnioId(FromUserName,accessToken);
				    HashMap hashMap = JSON.parseObject(res, HashMap.class);
				    String unioId = (String) hashMap.get("unionid");
				    TbWxuser table2 = JSON.parseObject(res, TbWxuser.class);
				    boolean falgpt=true;
				    if(StringUtils.isNoneBlank(unioId)) {
				    	TbWxuser userByUnioId = wxUserService.getUserByUnioId(unioId);
				    	if(userByUnioId != null) {
				    		falgpt=false;
				    		id=userByUnioId.getId();
				    		if(userByUnioId != null) {
					    		Integer wxuserId2 = userByUnioId.getWxuserId();
					    		String gzhOpenId = userByUnioId.getGzhOpenId();
					    		//判断是否有上级
					    		if(wxuserId2 == null) {
					    			userByUnioId.setWxuserId(Integer.valueOf(wxUserId));
					    		}
					    		if(!StringUtils.isNoneBlank(gzhOpenId)) {
					    			userByUnioId.setGzhOpenId(FromUserName);
					    		}
					    		userByUnioId.setStatus("1");
					    		wxUserService.insert2update(userByUnioId);
					    		id=userByUnioId.getId();
					    	}
				    	}else {
					    	table2.setOpenid(null);
				    		table2.setSid(sid+"");
				    		table2.setWxUnionId(unioId);
				    		table2.setWxuserId(Integer.valueOf(wxUserId));
				    		table2.setGzhOpenId(FromUserName);
				    		table2.setStatus("1");
				    		wxUserService.insert2update(table2);
				    		id=table2.getId();
				    		//发送模板消息
				    		TbWxuser byId = wxUserService.getById(Integer.valueOf(wxUserId));
						    String gzhOpenId = byId.getGzhOpenId();
						    if(gzhOpenId != null && gzhOpenId != "") {
						    	TbWeixinconfig selectByUserId = wxConfigService.selectByUserId(sid);
					            TemplateMsgRequest newUserJoin = TemplateMsgRequest.createNewUserJoin(gzhOpenId,null, table2.getNickname(), DateUtils.format(new Date()),selectByUserId.getServiceTemplate());
					            wXService.sendTemplateMsg(AppId, Appsecret, newUserJoin);
						    }
						    TbWeixinconfig selectByUserId2 = wxConfigService.selectByUserId(sid);
						    
						    TbWxmenu selectByUserId = wxMenuService.selectByUserId(sid);
						    List<TbScgl> list = scglService.list(selectByUserId.getId(),0);
					    	if(list != null && list.size() > 0) {
					    		for (TbScgl tbScgl : list) {
					    			Integer sclb = tbScgl.getSclb();
					    			if(sclb == 0) {
						    			sendMsg(accessToken,FromUserName, tbScgl.getTitile(), tbScgl.getAppUrl(),selectByUserId2.getAppid(),tbScgl.getCode());
					    			}else if(sclb == 1) {
					    				sendMsg3(accessToken, FromUserName, tbScgl.getTitile(), tbScgl.getScms(), bootdoConfig.getSsl()+tbScgl.getUrl(), tbScgl.getYmlj());
					    			}else if(sclb == 2) {
					    				sendMsg4(accessToken, FromUserName, tbScgl.getScms());
					    			}
								}
					    	}
//					    	sendMsg(accessToken,FromUserName,selectByUserId2.getAppid(),"Wr8SVx7Dgzgll4I2-xlgj-MfBPee5XYMZaJkE7CMhGc");
				    	}
				    }
					
				    //如果是新用户
				    if(falgpt) {
				    	//走拼团逻辑
						//拼团id
				    	String groupBuyId = split[2];
						//加入拼团的人id
						if(id != null) {
							UserGroupBuyVo joinGroupBuy = userGroupBuyService.joinGroupBuy(Integer.valueOf(groupBuyId), id+"");
							TbWxuser byId = wxUserService.getById(Integer.valueOf(wxUserId));
				    		String gzhOpenId = byId.getGzhOpenId();
							if(joinGroupBuy != null) {
					    		if(gzhOpenId != null && gzhOpenId != "") {
					    			List<GroupBuyJoinerVo> joiners = joinGroupBuy.getJoiners();
					    			String price = joinGroupBuy.getPrice();
					    			double aa=getDouble2String(price) - joiners.size();
					    			TbWeixinconfig selectByUserId = wxConfigService.selectByUserId(sid);
						            TemplateMsgRequest newUserJoin = TemplateMsgRequest.createKjcg(gzhOpenId,null, DateUtils.format(new Date()), aa+"","砍价成功",selectByUserId.getServiceTemplate4());
						            wXService.sendTemplateMsg(AppId, Appsecret, newUserJoin);
						            TemplateMsgRequest newUserJoin2 = TemplateMsgRequest.createKjcg(FromUserName,null, DateUtils.format(new Date()), aa+"","砍价成功",selectByUserId.getServiceTemplate4());
						            wXService.sendTemplateMsg(AppId, Appsecret, newUserJoin2);
							    }
				    		}else {
				    			if(gzhOpenId != null && gzhOpenId != "") {
					    			TbWeixinconfig selectByUserId = wxConfigService.selectByUserId(sid);
						            TemplateMsgRequest newUserJoin = TemplateMsgRequest.createKjcg(gzhOpenId,null, DateUtils.format(new Date()),"","砍价失败",selectByUserId.getServiceTemplate4());
						            wXService.sendTemplateMsg(AppId, Appsecret, newUserJoin);
						            TemplateMsgRequest newUserJoin2 = TemplateMsgRequest.createKjcg(FromUserName,null, DateUtils.format(new Date()),"","砍价失败",selectByUserId.getServiceTemplate4());
						            wXService.sendTemplateMsg(AppId, Appsecret, newUserJoin2);
							    }
				    		}
						}
				    }else {
				    	TbWxuser byId = wxUserService.getById(Integer.valueOf(wxUserId));
			    		String gzhOpenId = byId.getGzhOpenId();
			    		if(gzhOpenId != null && gzhOpenId != "") {
			    			TbWeixinconfig selectByUserId = wxConfigService.selectByUserId(sid);
				            TemplateMsgRequest newUserJoin = TemplateMsgRequest.createKjcg(gzhOpenId,null, DateUtils.format(new Date()),"","砍价失败,只支持新用户",selectByUserId.getServiceTemplate4());
				            wXService.sendTemplateMsg(AppId, Appsecret, newUserJoin);
				            TemplateMsgRequest newUserJoin2 = TemplateMsgRequest.createKjcg(FromUserName,null, DateUtils.format(new Date()),"","砍价失败,只支持新用户",selectByUserId.getServiceTemplate4());
				            wXService.sendTemplateMsg(AppId, Appsecret, newUserJoin2);
					    }
				    }
					//发送模板消息
//					TbWeixinconfig selectByUserId = wxConfigService.selectByUserId(Integer.valueOf(split[4]));
//		            TemplateMsgRequest newUserJoin = TemplateMsgRequest.createOrderConfirm(FromUserName,null, table2.getNickname(), table2.getSubscribeTime(),selectByUserId.getServiceTemplate2());
//		            wXService.sendTemplateMsg(AppId, Appsecret, newUserJoin);
				}else if("yq".equals(type))  {
					if(falg) {
						//走邀请逻辑
						String wxUserId = split[1];
//						String AppId = split[2];
//						String Appsecret = split[3];
						String accessToken= wXService.getAccessToken(AppId, Appsecret);
//					    String accessToken =WeiXinUtil.getOauth2AccessToken2(AppId, Appsecret);
					    String res = getUnioId(FromUserName,accessToken);
					    HashMap hashMap = JSON.parseObject(res, HashMap.class);
					    String unioId = (String) hashMap.get("unionid");
			    		TbWxuser table2 = JSON.parseObject(res, TbWxuser.class);
					    if(StringUtils.isNoneBlank(unioId)) {  
						    TbWxuser userByUnioId = wxUserService.getUserByUnioId(unioId);
						    if(userByUnioId != null) {
					    		if(userByUnioId != null) {
						    		String gzhOpenId = userByUnioId.getGzhOpenId();
						    		if(!StringUtils.isNoneBlank(gzhOpenId)) {
						    			userByUnioId.setGzhOpenId(FromUserName);
						    		}
						    		userByUnioId.setStatus("1");
						    		wxUserService.insert2update(userByUnioId);
						    	}
					    	}else{
						    	table2.setOpenid(null);
					    		table2.setSid(sid+"");
					    		table2.setWxUnionId(unioId);
					    		table2.setWxuserId(Integer.valueOf(wxUserId));
					    		table2.setGzhOpenId(FromUserName);
					    		table2.setStatus("1");
					    		wxUserService.insert2update(table2);
					    	}
						  //发送模板消息
						    TbWxuser byId = wxUserService.getById(Integer.valueOf(wxUserId));
						    String gzhOpenId = byId.getGzhOpenId();
						    if(gzhOpenId != null && gzhOpenId != "") {
						    	TbWeixinconfig selectByUserId = wxConfigService.selectByUserId(sid);
					            TemplateMsgRequest newUserJoin = TemplateMsgRequest.createNewUserJoin(gzhOpenId,null, table2.getNickname(), DateUtils.format(new Date()),selectByUserId.getServiceTemplate());
					            wXService.sendTemplateMsg(AppId, Appsecret, newUserJoin);
						    }
						    TbWeixinconfig selectByUserId2 = wxConfigService.selectByUserId(sid);
						    TbWxmenu selectByUserId = wxMenuService.selectByUserId(sid);
						    List<TbScgl> list = scglService.list(selectByUserId.getId(),0);
					    	if(list != null && list.size() > 0) {
					    		for (TbScgl tbScgl : list) {
					    			Integer sclb = tbScgl.getSclb();
					    			if(sclb == 0) {
						    			sendMsg(accessToken,FromUserName,tbScgl.getTitile(),tbScgl.getAppUrl(),selectByUserId2.getAppid(),tbScgl.getCode());
					    			}else if(sclb == 1) {
					    				sendMsg3(accessToken, FromUserName, tbScgl.getTitile(), tbScgl.getScms(), bootdoConfig.getSsl()+tbScgl.getUrl(), tbScgl.getYmlj());
					    			}else if(sclb == 2) {
					    				sendMsg4(accessToken, FromUserName, tbScgl.getScms());
					    			}
								}
					    	}
//					    	sendMsg(accessToken,FromUserName,selectByUserId2.getAppid(),"Wr8SVx7Dgzgll4I2-xlgj-MfBPee5XYMZaJkE7CMhGc");
					    }
					}
				}
			}else {
				if("subscribe".equals(Event)) {
					TbWxmenu selectByUserId = wxMenuService.selectByUserId(sid);
					String accessToken= wXService.getAccessToken(selectByUserId.getAppid(), selectByUserId.getAppsecret());
//					String accessToken =WeiXinUtil.getOauth2AccessToken2(selectByUserId.getAppid(), selectByUserId.getAppsecret());
				    String res = getUnioId(FromUserName,accessToken);
				    HashMap hashMap = JSON.parseObject(res, HashMap.class);
				    String unioId = (String) hashMap.get("unionid");
				    TbWxuser table2 = JSON.parseObject(res, TbWxuser.class);
				    if(StringUtils.isNoneBlank(unioId)) {
				    	TbWxuser userByUnioId = wxUserService.getUserByUnioId(unioId);
				    	if(userByUnioId != null) {
				    		if(userByUnioId != null) {
					    		String gzhOpenId = userByUnioId.getGzhOpenId();
					    		//判断是否有上级
					    		if(!StringUtils.isNoneBlank(gzhOpenId)) {
					    			userByUnioId.setGzhOpenId(FromUserName);
					    		}
					    		userByUnioId.setStatus("1");
					    		wxUserService.insert2update(userByUnioId);
					    	}
				    	}else {
					    	table2.setOpenid(null);
				    		table2.setSid(sid+"");
				    		table2.setWxUnionId(unioId);
				    		table2.setGzhOpenId(FromUserName);
				    		table2.setStatus("1");
				    		wxUserService.insert2update(table2);
				    	}
				    	//
				    	TbWeixinconfig selectByUserId2 = wxConfigService.selectByUserId(sid);
				    	
				    	List<TbScgl> list = scglService.list(selectByUserId.getId(),0);
				    	if(list != null && list.size() > 0) {
				    		for (TbScgl tbScgl : list) {
				    			Integer sclb = tbScgl.getSclb();
				    			if(sclb == 0) {
					    			sendMsg(accessToken,FromUserName,tbScgl.getTitile(),tbScgl.getAppUrl(),selectByUserId2.getAppid(),tbScgl.getCode());
				    			}else if(sclb == 1) {
				    				sendMsg3(accessToken, FromUserName, tbScgl.getTitile(), tbScgl.getScms(), bootdoConfig.getSsl()+tbScgl.getUrl(), tbScgl.getYmlj());
				    			}else if(sclb == 2) {
				    				sendMsg4(accessToken, FromUserName, tbScgl.getScms());
				    			}
							}
				    	}
				    	//发送模板消息
//			    		TbWeixinconfig tbWeixinconfig = wxConfigService.selectByUserId(sid);
//			            TemplateMsgRequest newUserJoin = TemplateMsgRequest.createNewUserJoin(FromUserName,null, table2.getNickname(), DateUtils.format(new Date()),tbWeixinconfig.getServiceTemplate());
//			            wXService.sendTemplateMsg(selectByUserId.getAppid(), selectByUserId.getAppsecret(), newUserJoin);
				    }
				}else if("unsubscribe".equals(Event)) {
					TbWxuser selectUserInfoByGzh = wxUserService.selectUserInfoByGzh(FromUserName);
			    	if(selectUserInfoByGzh != null) {
			    		selectUserInfoByGzh.setStatus("0");
			    		wxUserService.insert2update(selectUserInfoByGzh);
			    	}
				}
			}
		}
		
		private String getUnioId(String openId,String token) {
			String aa="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+token+"&openid="+openId+"&lang=zh_CN";
			String doGet = HttpUtil.doGet(aa, null);
			return doGet;
		}
		
		private Double getDouble2String(String num) {
			if(StringUtils.isNoneBlank(num)) {
				Double cny = Double.parseDouble(num);
				DecimalFormat df = new DecimalFormat("0.00000"); 
				String CNY = df.format(cny);
				Double cny1 = Double.parseDouble(CNY);
				return cny1;
			}
			return 0.00;
		}
		
		
		private void sendMsg(String accessToken,String openId,String title,String appUrl,String appid,String thumb_media_id){
			if(appUrl == null) {
				appUrl="pages/index/index";
			}
	         String strurl="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToken;
	         String responeJsonStr = "{";
	         responeJsonStr += "\"touser\": \"" + openId + "\",";
	         responeJsonStr += "\"msgtype\": \"miniprogrampage\",";
	         responeJsonStr += "\"miniprogrampage\": {";
	         responeJsonStr += "  \"title\": \"" + title + "\",";
	         responeJsonStr += "  \"appid\": \"" + appid + "\",";
	         responeJsonStr += "  \"pagepath\": \"" + appUrl + "\",";
	         responeJsonStr += "  \"thumb_media_id\": \"" + thumb_media_id + "\"";
	         responeJsonStr += "}";
	         responeJsonStr += "}";
			  System.out.println(responeJsonStr);
			  xstream.connectWeiXinInterface(strurl,responeJsonStr);
		}
		
		private void sendMsg3(String accessToken,String openId,String title,String description,String picurl,String url){
	        if(url == null) {
	        	url="";
	        }
			String strurl="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToken;
	        String responeJsonStr = "{";
	        responeJsonStr += "\"touser\": \"" + openId + "\",";
	        responeJsonStr += "\"msgtype\": \"news\",";
	        responeJsonStr += "\"news\": {";
	        responeJsonStr += "\"articles\": [{";
	        responeJsonStr += "  \"title\": \"" + title + "\",";
	        responeJsonStr +=	"  \"description\": \"" + description + "\",";
	        responeJsonStr += "  \"url\": \"" + url + "\",";
	        responeJsonStr += "  \"picurl\": \"" + picurl + "\",";
	        responeJsonStr += "}]";
	        responeJsonStr += "}";
	        responeJsonStr += "}";
			  System.out.println(responeJsonStr);
			  xstream.connectWeiXinInterface(strurl,responeJsonStr);
		}
		
		private void sendMsg4(String accessToken,String openId,String content){
	        String strurl="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToken;
	        String responeJsonStr = "{";
	        responeJsonStr += "\"touser\": \"" + openId + "\",";
	        responeJsonStr += "\"msgtype\": \"text\",";
	         responeJsonStr += "\"text\": {";
	         responeJsonStr += "  \"content\": \"" + content + "\",";
	         responeJsonStr += "}";
	        responeJsonStr += "}";
			  System.out.println(responeJsonStr);
			  xstream.connectWeiXinInterface(strurl,responeJsonStr);
		}
		
		private void sendMsg5(String accessToken,String openId,String mediaId){
	        String strurl="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToken;
	        String responeJsonStr = "{";
	        responeJsonStr += "\"touser\": \"" + openId + "\",";
	        responeJsonStr += "\"msgtype\": \"image\",";
	         responeJsonStr += "\"image\": {";
	         responeJsonStr += "  \"media_id\": \"" + mediaId + "\",";
	         responeJsonStr += "}";
	        responeJsonStr += "}";
			  System.out.println(responeJsonStr);
			  xstream.connectWeiXinInterface(strurl,responeJsonStr);
		}
		
		public static JSONObject addMaterialEver(String fileurl, String type, String token) {
	        try {
	            File file = new File(fileurl);
	            //上传素材
	            String path = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=" + token ;
	            String result = connectHttpsByPost(path, null, file);
	            result = result.replaceAll("[\\\\]", "");
	            System.out.println("result:" + result);
	            JSONObject resultJSON = JSONObject.fromObject(result);
	            if (resultJSON != null) {
	                if (resultJSON.get("media_id") != null) {
	                    System.out.println("上传" + type + "永久素材成功");
	                    return resultJSON;
	                } else {
	                    System.out.println("上传" + type + "永久素材失败");
	                }
	            }
	            return null;
	        } catch (IOException e) {
	            e.printStackTrace();
	        } catch (NoSuchAlgorithmException e) {
	            e.printStackTrace();
	        } catch (NoSuchProviderException e) {
	            e.printStackTrace();
	        } catch (KeyManagementException e) {
	            e.printStackTrace();
	        }
	        return null;
	    }
		
		public static String connectHttpsByPost(String path, String KK, File file) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
	        URL urlObj = new URL(path);
	        //连接
	        HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
	        String result = null;
	        con.setDoInput(true);

	        con.setDoOutput(true);

	        con.setUseCaches(false); // post方式不能使用缓存

	        // 设置请求头信息
	        con.setRequestProperty("Connection", "Keep-Alive");
	        con.setRequestProperty("Charset", "UTF-8");
	        // 设置边界
	        String BOUNDARY = "----------" + System.currentTimeMillis();
	        con.setRequestProperty("Content-Type",
	                "multipart/form-data; boundary="
	                        + BOUNDARY);

	        // 请求正文信息
	        // 第一部分：
	        StringBuilder sb = new StringBuilder();
	        sb.append("--"); // 必须多两道线
	        sb.append(BOUNDARY);
	        sb.append("\r\n");
	        sb.append("Content-Disposition: form-data;name=\"media\";filelength=\"" + file.length() + "\";filename=\""

	                + file.getName() + "\"\r\n");
	        sb.append("Content-Type:application/octet-stream\r\n\r\n");
	        byte[] head = sb.toString().getBytes("utf-8");
	        // 获得输出流
	        OutputStream out = new DataOutputStream(con.getOutputStream());
	        // 输出表头
	        out.write(head);

	        // 文件正文部分
	        // 把文件已流文件的方式 推入到url中
	        DataInputStream in = new DataInputStream(new FileInputStream(file));
	        int bytes = 0;
	        byte[] bufferOut = new byte[1024];
	        while ((bytes = in.read(bufferOut)) != -1) {
	            out.write(bufferOut, 0, bytes);
	        }
	        in.close();
	        // 结尾部分
	        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
	        out.write(foot);
	        out.flush();
	        out.close();
	        StringBuffer buffer = new StringBuffer();
	        BufferedReader reader = null;
	        try {
	            // 定义BufferedReader输入流来读取URL的响应
	            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
	            String line = null;
	            while ((line = reader.readLine()) != null) {
	                buffer.append(line);
	            }
	            if (result == null) {
	                result = buffer.toString();
	            }
	        } catch (IOException e) {
	            System.out.println("发送POST请求出现异常！" + e);
	            e.printStackTrace();
	        } finally {
	            if (reader != null) {
	                reader.close();
	            }
	        }
	        return result;
	    }
}
